<template>
  <!-- 商品卡片 -->
  <view :class="path=='index'?'minheight':''">
    <view class="homeqiehuan" v-if="path=='index'">
      <view class="qieitem" :class="state.leiinfo.type==item.type?'qieactive':''" v-for="(item,index) in state.leilist" :key="index" @click="ltypeClick(item)">
        <text class="qiename">{{ item.title }}</text>
        <text class="qiemiao">{{item.subtitle}}</text>
      </view>
    </view>
    <!-- 1 100%宽卡片列表-->
    <view v-if="mode === 1 && state.goodsList.length" class="goods-sl-box">
      <view
        class="goods-box"
        v-for="item in state.goodsList"
        :key="item.id"
        :style="[{ marginBottom: data.space * 2 + 'rpx' }]"
      >
        <s-goods-column
          class=""
          size="sl"
          :goodsFields="goodsFields"
          :tagStyle="tagStyle"
          :data="item"
          :titleColor="goodsFields.title?.color"
          :subTitleColor="goodsFields.subtitle.color"
          :topRadius="data.borderRadiusTop"
          :bottomRadius="data.borderRadiusBottom"
          @click="sheep.$router.go('/pages/goods/index', { id: item.id })"
        >
          <template v-slot:cart>
            <button class="ss-reset-button cart-btn" :style="[buyStyle]">
              {{ buyNowStyle.mode === 1 ? buyNowStyle.text : '' }}
            </button>
          </template>
        </s-goods-column>
      </view>
    </view>

    <!-- 2   双列瀑布流列表-->
    <view
      v-if="mode === 2 && state.goodsList.length"
      class="goods-md-wrap ss-flex ss-flex-wrap ss-col-top"
    >
      <view class="goods-list-box">
        <view
          class="left-list"
          :style="[{ paddingRight: data.space + 'rpx', marginBottom: data.space + 'px' }]"
          v-for="item in state.leftGoodsList"
          :key="item.id"
        >
          <s-goods-column
            class="goods-md-box"
            size="md"
            :goodsFields="goodsFields"
            :tagStyle="tagStyle"
            :data="item"
            :titleColor="goodsFields.title?.color"
            :subTitleColor="goodsFields.subtitle.color"
            :topRadius="data.borderRadiusTop"
            :bottomRadius="data.borderRadiusBottom"
            :titleWidth="330 - marginLeft - marginRight"
            @click="sheep.$router.go('/pages/goods/index', { id: item.id })"
            @getHeight="mountMasonry($event, 'left')"
          >
            <template v-slot:cart>
              <button class="ss-reset-button cart-btn" :style="[buyStyle]">
                {{ buyNowStyle.mode === 1 ? buyNowStyle.text : '' }}
              </button>
            </template>
          </s-goods-column>
        </view>
      </view>
      <view class="goods-list-box">
        <view
          class="right-list"
          :style="[{ paddingLeft: data.space + 'rpx', marginBottom: data.space + 'px' }]"
          v-for="item in state.rightGoodsList"
          :key="item.id"
        >
          <s-goods-column
            class="goods-md-box"
            size="md"
            :goodsFields="goodsFields"
            :tagStyle="tagStyle"
            :data="item"
            :titleColor="goodsFields.title?.color"
            :subTitleColor="goodsFields.subtitle.color"
            :topRadius="data.borderRadiusTop"
            :bottomRadius="data.borderRadiusBottom"
            :titleWidth="330 - marginLeft - marginRight"
            @click="sheep.$router.go('/pages/goods/index', { id: item.id })"
            @getHeight="mountMasonry($event, 'right')"
          >
            <template v-slot:cart>
              <button class="ss-reset-button cart-btn" :style="[buyStyle]">
                {{ buyNowStyle.mode === 1 ? buyNowStyle.text : '' }}
              </button>
            </template>
          </s-goods-column>
        </view>
      </view>
    </view>

    <!-- 3  30%卡片列表-->
    <view v-if="mode === 3 && state.goodsList.length" class="goods-lg-box">
      <view
        class="goods-box"
        :style="[{ marginBottom: data.space + 'px' }]"
        v-for="item in state.goodsList"
        :key="item.id"
      >
        <s-goods-column
          class="goods-card"
          size="lg"
          :goodsFields="goodsFields"
          :data="item"
          :tagStyle="tagStyle"
          :titleColor="goodsFields.title?.color"
          :subTitleColor="goodsFields.subtitle.color"
          :topRadius="data.borderRadiusTop"
          :bottomRadius="data.borderRadiusBottom"
          @tap="sheep.$router.go('/pages/goods/index', { id: item.id })"
        >
          <template v-slot:cart>
            <button class="ss-reset-button cart-btn" :style="[buyStyle]">
              {{ buyNowStyle.mode === 1 ? buyNowStyle.text : '' }}
            </button>
          </template>
        </s-goods-column>
      </view>
    </view>

    <uni-load-more
      v-if="state.pagination.total > 0"
      :status="state.loadStatus"
      :content-text="{
        contentdown: '上拉加载更多',
      }"
      @tap="loadmore"
    />
    <s-empty v-if="state.pagination.total === 0" icon="/static/soldout-empty.png" text="暂无商品">
    </s-empty>
  </view>
</template>

<script setup>
  /**
   * 商品模板，装修商品卡片
   * @description style 1:带tab 2：瀑布流，横向两个，上图下内容 3：大图，横向一个
   */
  import { computed, reactive, onMounted } from 'vue';
  import { onLoad, onReachBottom } from '@dcloudio/uni-app';
  import sheep from '@/sheep';
  import _ from 'lodash';

  const state = reactive({
    goodsList: [],
    leftGoodsList: [],
    rightGoodsList: [],
    pagination: {
      data: [],
      current_page: 1,
      total: 1,
      last_page: 1,
    },
    currentSort: 'weigh',
    currentOrder: 'desc',
    categoryId: 0,
    keyword:'',
    loadStatus: '',
    leilist:[],
    leiinfo:{
      type:''
    }
  });
  const props = defineProps({
    data: {
      type: Object,
      default() {},
    },
    styles: {
      type: Object,
      default() {},
    },
    path:{
      type: String,
      default: '',
    }
  });

  const { mode, tagStyle, buyNowStyle, goodsFields, goodsIds } = props.data ?? {};
  const { marginLeft, marginRight } = props.styles ?? {};

  async function getGoodsListByIds(ids) {
    let { data } = await sheep.$api.goods.ids({ ids });
    return data;
  }

  // onLoad(async () => {
  //   // state.goodsList = await getGoodsListByIds(goodsIds.join(','));
  //   // console.log(state.goodsList)
  //   // if (mode === 2) {
  //   //   console.log("首页加载193行") 
  //   //   getleitype();//
  //   //   // getList(state.currentSort, state.currentOrder, state.categoryId, state.keyword);
  //   // }
  //   console.log("首页加载207行") 
  //   getleitype();
    
  // });
  onLoad((options) => {
    // console.log("首页加载212行") 
    // getleitype();
  });
  onMounted(async () => {
    // console.log("首页加载216行") 
    getleitype();
  });
  uni.$on('SELECT_HomeList', (e) => {
    console.log("接受通知首页")
   
    setTimeout(function () {
      jiance(e)
    },1000);
      

  });
  async function jiance(e){//处理首页列表加购数量
    console.log(e) 
    let goods_id = e.goods_id
    let type = e.type
    let leftGoodsList = state.leftGoodsList
    let rightGoodsList = state.rightGoodsList
    let goodsList = state.goodsList
    for(let i in goods_id){
      // setTimeout(function () {
      //   jiancetwo(goods_id[i])
      // },1000);
      const res = await sheep.$api.goods.getGoodsCartNums({
        goods_id:goods_id[i]
      });
      if(res.code == 1){
        for(let j in goodsList){
          if(goodsList[j].id == goods_id[i]){
            if(type == '1'){
              goodsList[j].cart_nums = res.data.nums
            }else if(type == '2'){
              goodsList[j].cart_nums = 0
            }
            
          }
        }
        // console.log(goodsList)
        state.goodsList = goodsList
        mountMasonry();
      }
    }
  
}

  // 加载瀑布流
  let count = 0;
  let leftHeight = 0;
  let rightHeight = 0;

  function mountMasonry(height = 0, where = 'left') {
    if (!state.goodsList[count]) return;
    if (where === 'left') leftHeight += height;
    if (where === 'right') rightHeight += height;
    if (leftHeight <= rightHeight) {
      state.leftGoodsList.push(state.goodsList[count]);
    } else {
      state.rightGoodsList.push(state.goodsList[count]);
    }
    // console.log( state.leftGoodsList)
    count++;
  }

  // 购买按钮样式
  const buyStyle = computed(() => {
    // console.log(`linear-gradient(to right, ${buyNowStyle.color1}, ${buyNowStyle.color2})`)
    if (buyNowStyle.mode == 1) {
      // button
      return {
        background: `linear-gradient(to right, ${buyNowStyle.color1}, ${buyNowStyle.color2})`,
      };
    }

    if (buyNowStyle.mode == 2) {
      // image
      return {
        width: '54rpx',
        height: '54rpx',
        background: `url(${sheep.$url.cdn(buyNowStyle.src)}) no-repeat`,
        backgroundSize: '100% 100%',
      };
    }
  });
  async function getleitype(){
    const res = await sheep.$api.goods.getSearchType({
      
    });
    state.leilist = res.data
    state.leiinfo = res.data[0]
    getList(state.currentSort, state.currentOrder, state.categoryId, state.keyword,state.pagination.current_page);
  }
  function ltypeClick(item){
    state.leiinfo = item
    state.pagination.data = []
    state.pagination.current_page = 1
    state.goodsList = []
    state.loadStatus = 'more';
    state.leftGoodsList = []
    state.rightGoodsList = []
    count =0
    leftHeight =0
    rightHeight = 0
    // console.log(state.goodsList)
    getList(
      state.currentSort,
      state.currentOrder,
      state.categoryId,
      state.keyword
    );
  }
  async function getList(Sort, Order, categoryId, keyword, page = 1, list_rows = 6) {//leiinfotype
    state.loadStatus = 'loading';
    const res = await sheep.$api.goods.list({
      sort: Sort,
      order: Order,
      category_id: !keyword ? categoryId : '',
      list_rows,
      keyword: keyword,
      page:state.pagination.current_page,
      type:state.leiinfo.type||''
    });
    // console.log(res.data.data)
    if (res.code === 1) {
      let couponList = _.concat(state.pagination.data, res.data.data);
      state.pagination = {
        ...res.data,
        data: couponList,
      };
      state.goodsList = state.pagination.data
      // console.log(state.goodsList)
      mountMasonry();
      if (state.pagination.current_page < state.pagination.last_page) {
        state.loadStatus = 'more';
      } else {
        state.loadStatus = 'noMore';
      }
    
    }
  }
  // 加载更多
  function loadmore() {
    if (state.loadStatus !== 'noMore') {
      state.pagination.current_page++
      getList(
        state.currentSort,
        state.currentOrder,
        state.categoryId,
        state.keyword
      );
    }
  }
  // 上拉加载更多
  onReachBottom(() => {
    loadmore();
  });
</script>

<style lang="scss" scoped>
  .goods-md-wrap {
    width: 100%;
  }

  .goods-list-box {
    width: 50%;
    box-sizing: border-box;
    .left-list {
      &:nth-last-child(1) {
        margin-bottom: 0 !important;
      }
    }
    .right-list {
      &:nth-last-child(1) {
        margin-bottom: 0 !important;
      }
    }
  }

  .goods-box {
    &:nth-last-of-type(1) {
      margin-bottom: 0 !important;
    }
  }

  .goods-md-box,
  .goods-sl-box,
  .goods-lg-box {
    position: relative;

    .cart-btn {
      position: absolute;
      bottom: 18rpx;
      right: 20rpx;
      z-index: 11;
      height: 50rpx;
      line-height: 50rpx;
      padding: 0 20rpx;
      border-radius: 25rpx;
      font-size: 24rpx;
      color: #fff;
    }
  }

  .homeqiehuan{
    display: flex;
    flex-direction: row;
    margin: 30rpx 0;
    .qieitem{
      display: flex;
      flex-direction: column;
      padding: 0 20rpx;
      display: flex;
      flex: 1;
      align-items: center;
      justify-content: center;
      .qiename{
        color: #333;
        font-size: 30rpx;
        font-weight: 400;
        display: inline-block;
        margin-bottom: 10rpx; 
      }
      .qiemiao{
        padding: 4rpx 10rpx;
        color: #666;
        font-size: 25rpx;
        font-weight: 400;
        border-radius: 50rpx;
      }
    }
    .qieactive{ 
      .qiename{
        color: #FF3000;
      }
      .qiemiao{
        background-color: #FF3000;
        color: #fff;

      }
    }
  }
  .minheight{
    min-height: 65vh;
  }
</style>
